package com.uuuo.rxjavaandretrofit.gson;


import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * Created by JiaTao on 2018/9/10.
 * Email: 535318720@qq.com
 * Version: 1.0
 * Description:
 */
public class DateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
    private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    public JsonElement serialize(Date ts, Type t, JsonSerializationContext jsc) {
        String dfString = format.format(new Date(ts.getTime()));
        return new JsonPrimitive(dfString);
    }

    public Date deserialize(JsonElement json, Type t, JsonDeserializationContext jsc) throws JsonParseException {
        if (!(json instanceof JsonPrimitive)) {
            throw new JsonParseException("The date should be a string value");
        }

        try {
            long longTime = Long.parseLong(json.getAsString());
            Date date = parseServerTime(longTime, null);
            return date;
        } catch (ParseException e) {
            throw new JsonParseException(e);
        }
    }

    public Date parseServerTime(long serverTime, String format) throws ParseException {
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINESE);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));

        Timestamp now = new Timestamp(serverTime);// 获取系统当前时间
        String formatStr = sdf.format(now);
        Date date = sdf.parse(formatStr);
        return date;
    }
}